package com.joe.codemother.aop;

import cn.hutool.core.bean.BeanUtil;
import com.joe.codemother.annotation.AuthCheck;
import com.joe.codemother.entity.User;
import com.joe.codemother.entity.enums.UserRoleEnums;
import com.joe.codemother.exception.BusinessException;
import com.joe.codemother.exception.ErrorCode;
import com.joe.codemother.service.UserService;
import com.joe.codemother.util.ThrowUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doAuthInterceptor(ProceedingJoinPoint pjp, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        UserRoleEnums mustEnums = UserRoleEnums.getEnumByValue(mustRole);
        UserRoleEnums userRoleEnums = UserRoleEnums.getEnumByValue(loginUser.getUserRole());
        if(BeanUtil.isEmpty(mustEnums)){
            return pjp.proceed();
        }
        ThrowUtils.throwIf(BeanUtil.isEmpty(userRoleEnums),ErrorCode.PARAMS_ERROR,"no role exist!");
        if(userRoleEnums.equals(mustEnums) || userRoleEnums.equals(UserRoleEnums.Admin)){
            return pjp.proceed();
        }else{
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

}
